<?
session_start();
$html_output = true;
// Only make conservative edits if a_o = 0; more guesswork-based edits under higher values
$ambitious_output = 9;
if ($_REQUEST["submit"]) {
  $always_display = $_REQUEST["always_display"];
  $extinct = $_REQUEST["extinct"];
  $new_taxon = ucfirst(trim($_REQUEST["taxon"]));
  $new_taxon_display = trim($_REQUEST["taxon_display"]?$_REQUEST["taxon_display"]:$new_taxon);
  $new_link = trim($_REQUEST["taxon_link"]);
  $new_rank = trim($_REQUEST["rank"]);
  $parent_id = trim($_REQUEST["parent"]);
  $redirect_source = trim($_REQUEST["redirect_from"]);
  $inherited_link = trim($_REQUEST["parent_link"]);
  $new_code = "{{Don't edit this line {{{machine code|}}}|{{{1}}}
|rank=" . strtolower($new_rank) . "
|link=" . (($new_link && $new_link != $new_taxon_display)?"$new_link|":"") . $new_taxon_display .  "
|parent=" . ucfirst($parent_id) .
  ($extinct?"\n|extinct=true":"") .
  ($always_display?"\n|always_display=true":"") . "
}}
";
  // Save the created data to Session
  $_SESSION["created_taxa"][$_REQUEST["creation_count"]] = array("name" => $new_taxon, "rank" => $new_rank, "link" => $new_link);
  $current_taxon = $parent_id;
  $page = $inherited_link ? $inherited_link : $parent_id;
} else {
  $current_taxon = $_REQUEST["taxon"];
  $page = $current_taxon;
}
if (!$page) {
  header("location: ./taxobot.html");
}
include("boot.php");

if ($_REQUEST["new_query"]) {
  session_destroy();
  session_start();
  $_SESSION["user"] = $_POST["user"];
  $_SESSION["original_query"] = $page;
}

if ($new_taxon) {
  $source = $_REQUEST["source"];
  $user = $_SESSION["user"];
  $valid_user = is_valid_user($user);
  if ($valid_user) {
    $edit_summary = "+Taxonomic info from \"" . ($source?$source:"unspecified source") . "\"; User: [[User:$user|$user]]";
    $taxonomy_page = "Template:Taxonomy/" . ucfirst(wikititle_encode($new_taxon));
    $redirecting_page = "Template:Taxonomy/" . wikititle_encode($redirect_source);
    if (getArticleId($taxonomy_page)) {
      $target_is_there = true;
      $message = "<p>Page already exists at $taxonomy_page.  New code was <pre>$new_code
      \nEdit Summary:  $edit_summary</pre></p>";
    } else {
      $message = "<p>Created new page at <a href='" . wikiroot . "title=" . urlencode($taxonomy_page) . "'
      title='View on Wikipedia'>$taxonomy_page</a>.";
      if ($valid_user) {
        $write_success = ("Success" == write($taxonomy_page, $new_code, $edit_summary));
        $target_is_there = $write_success;
// if this returns Success, we should use the message above.
      } else {
        $target_is_there = false;
        if (development_mode()) {
          $message .= "<pre>$new_code\nEdit summary: $edit_summary</pre></p>";
        }
      }
    }
  } else {
    $edit_summary = "+Taxonomic info from \"" . ($source?$source:"unspecified source") . "\"; User: [[User:$user|$user]]\n"
                  . "\nSession was not initiated by valid user; edit will not be completed";
    if (getArticleId("Template:Taxonomy/$new_taxon")) {
      $message = "<p>Page already exists at Template:Taxonomy/$new_taxon.  New code was <pre>$new_code
      \nEdit Summary:  $edit_summary</pre></p>";
    } else {
      $message = "<p>Created new page at <a href='" . wikiroot . "title=Template:Taxonomy/" . wikititle_encode($new_taxon) . "'
      title='View on Wikipedia'>Template:Taxonomy/$new_taxon</a>. <pre>$new_code
      \nEdit summary: $edit_summary</pre></p>";
    }
  }
}


if ($valid_user) {
  $editSummaryEnd = "[[User:$user|$user]]";
  $user_id = $user;
} else {
  $editSummaryEnd = "User-activated.";
  $user_id = false;
  print "You must specify your Wikipedia username.  Edits will not be committed, but a mock-up of
    the bot's output is displayed below.";
}

$editInitiator = "[" . revisionID() . "]";

?>
<body class="mediawiki ns-2 ltr page-User_taxobot">
	<div id="globalWrapper">
		<div id="column-content">
	<div id="content">
<h1 class="firstHeading">Taxobot: Wikipedia taxonomy generation</h1>
<div id="bodyContent">
	<h3 id="siteSub">
    Creating taxonomy for <?=$page?>.
    Initialized by <?=$user_id?"<a href='" . wikiroot . "title=User:$user_id'>$user_id</a>":"anonymous user"?>.
    Script version r<?=revisionID()?>.
  </h3>
  <?=$message?>
 <p>
<?

$linked_to_existing_taxonomy = getArticleId("Template:Taxonomy/" . $page);
$nonredirected_page = $page;
//TODO: don't print message unless necessary
do {
  $page_id = isRedirect($page);
  switch ($page_id[0]) {
    case -1:
      $message = wikiLink($page, "darkred") . " does not exist.";
      break;
      $is_redirect = false;
    case 1:
      $message = "$page redirects";
      $raw_page = getRawWikitext($page);
      if (preg_match("~\[\[(.+)\]\]~i", $raw_page, $match)) {
        $page = $match[1];
        $message .= " to $page.\n";
      } else if ($raw_page) {
        $message .= " but in an unusual format: " .  $raw_page;
        die ("<pre>$message\nPlease report this bug at [[User talk:Taxobot]].  " . getRawWikitext($page));
      } else {
        die ("Wikipedia's servers apppear to be too busy.  Try a refresh (hit F5) in a moment or two.");
      }
      $is_redirect = true;
      break;
    case 0:
      $message = "An article exists at <a href=\"" . wikiroot . "title=" . urlencode($page) . "\">$page</a>; ";
      $content = getRawWikitext($page, true);
      $taxobox = extract_template($content, "taxobox");
      if (!$taxobox) {
        $automatic_taxobox = extract_template($content, "automatic taxobox");
        if ($automatic_taxobox) {
          $message .= "an automatic taxobox is present.";
        } else {
          $message .= "no taxobox was found.  (It could be absent, or the server could be too busy.)";

          if (!$parent_link) {
            $parent_link = $_SESSION["parent_links"];
            $page = $parent_link[1];
            $message = " Let's try $page instead. ";
            $is_redirect = true;
          } else {
            $is_redirect = false;
          }
        }
        //$linked_to_existing_taxonomy = true;
      } else {
        $message .= "its taxobox has been fetched.";
        $is_redirect = false;
      }
      break;
  }
} while ($is_redirect);
if ($linked_to_existing_taxonomy) {
  // Nothing more to be done.  Try to automate the taxobox?
  $automated_taxobox = automate_taxobox($taxobox);
  $origin = $_SESSION["original_query"];
  if ($taxobox) {
    print rm_errormsg(parse_wikitext($taxobox, $page));
    $taxo_style = "text-align: left; width: 200px";
    print rm_errormsg(str_replace($taxo_style, "clear: none; border-style: dashed; " . $taxo_style, parse_wikitext($automated_taxobox, $page))) . "Taxonomy ";
  } else if (getArticleId($page)) {
    print "An automatic taxobox";
  } else {
    print "No article";
  }
  ?> exists at <b><?=$page?></b>. <?print_links($page)?>
  <br />Thank you! You've linked <b><?=$origin?></b> <? print_links($origin);?> to the tree of life.</p>
 <p>Would you like to <a href="taxobot.html" title="Start again">automate another taxon</a>?</p><?
  if (false && $_SESSION["parents"]) {
    print "<p>Or you can upgrade the following articles to an automatic taxobox:<ul>";
    print upgrade_button(array("taxon" => $parent_id, "link" => $page, "rank" => "This taxon"), $taxobox, $automated_taxobox);
    foreach ($_SESSION["created_taxa"] as $list_item) {
      print upgrade_button($list_item);
    }
    print "</ul></p>";
  }
 ?>
  <? if ($taxobox) {/*?>
    <p>The following code (whose product is illustrated here with a dashed border)
    represents the bot's proposed conversion of the existing taxobox at <?=$page?> (displayed with solid border)
    to the {{Automatic taxobox}} template.  Your feedback on this feature is welcome at
    [[<a href="http://en.wikipedia.org/wiki/Wikipedia:BRFA#Taxobot_3">WP:BRFA#Taxobot 3</a>]].</p>
 <pre style='overflow:scroll'><?=htmlspecialchars($automated_taxobox)?></pre>
<? */}
} else {
  // Try to extract taxonomic information
  $using_previous = false;
  $inomial = null;
  if ($taxobox) {
    $existing_taxobox = rm_errormsg(parse_wikitext($taxobox, $page));
    $_SESSION["last_taxobox"] = $existing_taxobox;
    print $existing_taxobox ? $existing_taxobox : "<p class=error>Taxobox preview temporarily unavailable. (Try refreshing this page.)</p>";
    #print "<pre>  ";
    $rank_regexp = "~\|\s*%s\s*=" . '(' . "[^\[\|]*\[\[([\w\.\(\) #]*?\|?)?([\w\.\(\) ]+)\]\](\w*)" // Match the target of a link
                      . '|' . "[^\|\[]*?([\w\. ]+)\b" . // or match the first word of a '''formatted-taxon'''
              ')~i';
        // $match[ 1 ] = value of rank parameter
        // $match[ 2 ] = Link *target* or start of formatted line
        // $match[ 3 ] = Text displayed in link (if link present, else null)
        // $match[ 4 ] = Anything following a link; e.g. [[Arthopod]]*a*.  (Will alternatively just match the fill text)
        // $match[ 5 ] = \w+ with accompanying formatting removed

    if (preg_match(sprintf($rank_regexp, "([trb]+)inomial"), $taxobox, $match)) {
          // If binomial (or trinomial) is specified, we should ideally take the text ofthe (sub)species field for the displaytext
          // and use the (tri/)binomial as a taxon name; i.e. create the page Tempalte:Taxonomy/trinomial.sp.ssp.
      $inomial = trim($match[4] . $match[5] . $match[6]); // only 3 or 4 will be set; see description above
      $inomial_type = $match[1];
    }
    $i = 0;
    foreach ($taxonomic_ranks as $rank) {
      if (preg_match(sprintf($rank_regexp, $rank), $taxobox, $match)) {
        $this_taxon_name = trim($match[3] . $match[4] . $match[5]);
        #pre($this_taxon_name, $match);
        if ($bold_rank) {
          $bold_parent = trim($match[3] . $match[4] . $match[5]);
          print "<p>$bold_rank: $bold_taxon (parent: $bold_parent)"
              . "<a href='?taxon=$bold_taxon&taxon_link=$page&rank=$bold_rank&parent=$bold_parent&source=Existing+taxobox&submit=gogogo'>[Create]</a></p>";
        }
        if (strpos($match[1], "'''") !== FALSE) {
          $bold_rank= trim($rank);
          $bold_taxon = trim($match[3] . $match[4] . $match[5]);
        } else {
          $bold_rank = null;
          $bold_taxon = null;
        }
        // This check is intended to catch cases where the new taxon is monotypic and redirects to one of its children.
        if ($this_taxon_name == $current_taxon) {
          // If this is the case, we clear our memory of everything below this rank and start filling $parent (etc) again.
          $parent = null;
          $parent_link = null;
          $use_parent_link = null;
          $parent_rank = null;
          $i = 0;
        }

        // Now we put the information about the (grand)* parent into an array, which we'll later save to the $_SESSION
        $parent[$i] = trim($match[3] . $match[4] . $match[5]); // only 3 or 4 will be set; see description above
        $parent_link[$i] = trim(str_replace("|", "", $match[2]));
        $use_parent_link = strpos($parent[$i], ".");
        $parent_rank[$i] = trim($rank);

      } else {
        $use_parent_link = false;
      }
    }
    ++$i;

    if ($parent) {
      // $parent has been filled with each level of the taxobox, from the bottom upwards
      // $parent[0]  is the current taxon.
      $_SESSION["parents"] = $parent;
      $_SESSION["parent_ranks"] = $parent_rank;
      $_SESSION["parent_links"] = $parent_link;
      $_SESSION["parent_levels_used"] = 0;
    }
    #print "</pre>";
  }
}